package br.com.moxeon.control;

import java.util.ArrayList;
import java.util.Date;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import br.com.moxeon.model.enums.CheckOperation;
import br.com.moxeon.model.enums.CheckSituation;
import br.com.moxeon.model.financialitems.Check;
import br.com.moxeon.model.financialitems.CheckActions;
import br.com.vexillum.util.Message;
import br.com.vexillum.util.Return;

@Service
@Scope("prototype")
public class CheckController<E extends Check> extends MoxeonBaseController<E>{

	public CheckController(Class<E> classEntity) {
		super(classEntity);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Return save()
	{
		Integer numberCheck = (Integer) getData().get("numberCheck");
		Return result = new Return(true);
		if (numberCheck == null)
		{
			return new Return(false,new Message(null, "Nenhum cheque enviado para cadastro"));
		}
		for (Integer i=numberCheck;i>0;i--)
		{
			E nextEntity = (E) entity.cloneEntity();
			Integer entityNumber = Integer.parseInt(entity.getNumber());
			nextEntity.setNumber(String.valueOf(entityNumber + 1));
			executeCheckAction(CheckOperation.CADASTRO);
			result.concat(super.save());
			entity = nextEntity;
		}
		return result;
	}

	/*
	 * Passar para uma outra classe
	 */
	private void executeCheckAction(CheckOperation operation) {
		if (operation == CheckOperation.CADASTRO)
		{
			CheckActions action = new CheckActions();
			action.setCheck(entity);
			action.setActive(true);
			//action.setObservation("Cadasatrado com 5 cheques")
			action.setCheckOperation(operation);
			action.setDate(new Date());
			entity.setSituation(CheckSituation.ABERTO);
			addAction(action);
		}
	}

	private void addAction(CheckActions action) {
	    if (entity.getActions() == null)
	    {
	    	entity.setActions(new ArrayList<CheckActions>());
	    }
	    entity.getActions().add(action);
	}
	
	/*
	 * 
	 * substituir pela classe de realizar operação genérica
	 * ENND
	 */
	
	
}
